//
//  TTXML.m
//  Tint
//
//  Created by Kevin Wu on 4/19/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "TTXML.h"

@implementation TTXML


#pragma mark - Accessors

- (TTXMLNode *)rootElement
{
    TTRelease(_rootElement);
    if ( _XMLDocument ) {
        xmlNodePtr rootNode = xmlDocGetRootElement(_XMLDocument);
        if ( rootNode ) {
            _rootElement = [[TTXMLNode alloc] initWithXMLNodePtr:rootNode];
        }
    }
    return _rootElement;
}

- (NSData *)XMLData
{
    TTRelease(_XMLData);
    if ( _XMLDocument ) {
        
        xmlChar *buffer = NULL;
        int bufferSize = 0;
        
        xmlDocDumpMemory(_XMLDocument, &buffer, &bufferSize);
        
        if ( buffer ) {
            NSData *data = [[NSData alloc] initWithBytes:buffer length:bufferSize];
            xmlFree(buffer);
            _XMLData = data;
        }
        
    }
    return _XMLData;
}




#pragma mark - Memory

- (id)initWithXMLString:(NSString *)string
{
    NSData *data = [string newDataUsingUTF8StringEncoding];
    id xml = [self initWithXMLData:data];
    TTRelease(data);
    return xml;
}

- (id)initWithXMLData:(NSData *)data
{
    self = [super init];
    if ( self ) {
        _XMLDocument = xmlReadMemory((const char*)[data bytes], (int)[data length], NULL, NULL, XML_PARSE_NOCDATA | XML_PARSE_NOBLANKS);
    }
    return self;
}

- (id)initWithRootName:(NSString *)name
{
    self = [super init];
    if ( self ) {
        _XMLDocument = xmlNewDoc((const xmlChar*)"1.0");
        if ( _XMLDocument ) {
            
            _XMLDocument->encoding = (const xmlChar *)("utf-8");
            
            xmlNodePtr node = xmlNewNode(NULL, (const xmlChar *)[name UTF8String]);
            xmlDocSetRootElement(_XMLDocument, node);
        }
    }
    return self;
}

- (void)dealloc
{
    if ( _XMLDocument ) {
        xmlFreeDoc(_XMLDocument);
    }
    TTRelease(_rootElement);
    TTRelease(_XMLData);
    [super dealloc];
}

@end
